package com.yycx.module.bus.provider.handler.haiying.saleman;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.SaveInterceptor;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.module.bus.client.entity.BusCustom;
import com.yycx.module.bus.client.entity.BusDept;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.entity.BusSaleman;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.client.enums.DeptTypeEnum;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.handler.haiying.HyOrderUtils;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.HyErpSearchService;
import com.yycx.module.bus.provider.service.hy.HyOrderDetailService;
import com.yycx.module.bus.provider.service.hy.HyRemoteOrderService;
import com.yycx.module.system.client.entity.SysBank;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.provider.service.SysAreaService;
import com.yycx.module.system.provider.service.SysBankService;
import com.yycx.module.system.provider.service.SysCompanyService;
import com.yycx.module.user.client.entity.AppPosition;
import com.yycx.module.user.provider.service.AppPositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.MessageFormat;

/**
 * 海鹰业务员保存或者更新处理器
 *
 * @author zyf
 */
@Component
public class HySaleManSaveHandler implements SaveInterceptor<BusSaleman> {
    @Resource
    private BusDeptService deptService;


    @Resource
    private SysCompanyService companyService;


    @Resource
    private AppPositionService positionService;


    @Autowired
    @Lazy
    private BusSalemanService salemanService;


    @Autowired
    @Lazy
    private HyOrderUtils hyOrderUtils;


    @Override
    public void prepare(CriteriaSave cs, EntityMap entityMap, BusSaleman saleMan) {
        initBusSaleMan(saleMan);
        //未审批
        saleMan.setSalemanState(-2);
    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, BusSaleman saleMan) {

    }


    @Override
    public void prepare(CriteriaUpdate cu, EntityMap entityMap, BusSaleman saleMan) {
        //人员类型(1:业务员 2:部门人员)
        Integer saleManType = FlymeUtils.getInteger(saleMan.getSaleManType(), 1);
        if (saleManType.equals(1)) {
            initBusSaleMan(saleMan);
        }
    }

    @Override
    public void complete(CriteriaUpdate cu, EntityMap params, BusSaleman saleMan) {
    }


    /**
     * 初始化业务员
     *
     * @param busSaleman
     */
    private void initBusSaleMan(BusSaleman busSaleman) {
        Long companyId = FlymeUtils.getLong(busSaleman.getCompanyId(), OpenHelper.getCompanyId());
        Long deptId = busSaleman.getDeptId();
        BusDept busDept = deptService.getById(deptId);
        String deptCode = busDept.getDeptCode();
        ApiAssert.isNotEmpty("部门编码未设置", deptCode);
        busSaleman.setDeptType(busDept.getDeptType());
        //职务ID
        Long positionId = FlymeUtils.getLong(busSaleman.getPositionId(), 7L);
        String positionNo = "";
        if (FlymeUtils.isNotEmpty(positionId)) {
            AppPosition position = positionService.getById(positionId);
            positionNo = position.getPositionNo();
            busSaleman.setPositionId(positionId);
            ApiAssert.isNotEmpty("职务编码未设置", positionNo);
        }
        //部门类型
        String deptType = busDept.getDeptType();
        if (DeptTypeEnum.ZY.getCode().equals(deptType)) {
            //检测自营业务员是否存在
            checkZySaleMan(busSaleman);
            Long parentId = busSaleman.getParentId();
            //ApiAssert.isNotEmpty("请选择招募人", parentId);
            //业务编码 {招募人部门编码}{招募人职务编码}{招募人职务序号}{区域编码}{业务员唯一编码};
            String rule = "{0}{1}{2}{3}{4}";
            //唯一编码
            String saleManCode = getSaleManCode(busSaleman, companyId);
            //招募人
            if (FlymeUtils.isNotEmpty(parentId)) {
                //招募人
                BusSaleman parent = salemanService.getById(parentId);
                Long parentPositionId = parent.getPositionId();
                if (FlymeUtils.isNotEmpty(parentPositionId)) {
                    AppPosition parentPosition = positionService.getById(parentPositionId);
                    String parentPositionNo = parentPosition.getPositionNo();
                    String parentPositionOrder = parent.getPositionOrder();
                    String areaShortName = salemanService.getAreaShortName(busSaleman);
                    String saleManBusinessNo = MessageFormat.format(rule, deptCode, parentPositionNo, parentPositionOrder, areaShortName, saleManCode);
                    busSaleman.setSaleManBusinessNo(saleManBusinessNo);
                    busSaleman.setParentName(parent.getSaleManName());
                }
                String orderNum = getOrderNum(busSaleman);
                busSaleman.setOrderNum(orderNum);
            }

        }
        String saleManBusinessNo = busSaleman.getSaleManBusinessNo();
        if (DeptTypeEnum.ZS.getCode().equals(deptType) && FlymeUtils.isEmpty(saleManBusinessNo)) {
            //检测业务员是否存在
            checkSaleMan(busSaleman, companyId, 1);
            //职务序号
            String positionOrder = getPositionOrder(busSaleman, companyId, deptType);
            saleManBusinessNo = MessageFormat.format("{0}{1}", deptCode, positionOrder);
            busSaleman.setSaleManCode(null);
            busSaleman.setOrderNum(saleManBusinessNo);
            busSaleman.setSalemanState(1);

        }
        busSaleman.setSaleManBusinessNo(saleManBusinessNo);
        SysCompany company = companyService.getById(companyId);
        Long organizationId = company.getOrganizationId();
        busSaleman.setPositionCode(null);
        busSaleman.setHeadCode(null);
        busSaleman.setCompanyId(companyId);
        busSaleman.setOrganizationId(organizationId);
    }


    private Boolean checkSaleMan(BusSaleman busSaleman, Long companyId, Integer saleManType) {
        //职务序号
        CriteriaQuery cq = new CriteriaQuery(BusSaleman.class);
        cq.eq(FlymeUtils.isNotEmpty(busSaleman.getCardNo()), "cardNo", busSaleman.getCardNo());
        cq.eq(FlymeUtils.isNotEmpty(busSaleman.getSaleManName()), "saleManName", busSaleman.getSaleManName());
        cq.eq(true, "deptId", busSaleman.getDeptId());
        cq.eq(true, "positionId", busSaleman.getPositionId());
        cq.eq(true, "companyId", companyId);
        cq.eq(true, "saleManType", saleManType);
        cq.eq(FlymeUtils.isNotEmpty(busSaleman.getPositionOrder()), "positionOrder", busSaleman.getPositionOrder());
        cq.ne(FlymeUtils.isNotEmpty(busSaleman.getSaleManId()), "saleManId", busSaleman.getSaleManId());
        //检测同部门同职务同职务序号的人是否存在
        Long userCount = salemanService.count(cq);
        ApiAssert.lezero("人员已存在,请勿重复添加", userCount.intValue());
        return true;
    }

    /**
     * 检测自营业务员是否存在(按身份证检测)
     *
     * @param busSaleman
     * @return
     */
    private Boolean checkZySaleMan(BusSaleman busSaleman) {
        CriteriaQuery cq = new CriteriaQuery(BusSaleman.class);
        cq.eq(true, "cardNo", busSaleman.getCardNo());
        cq.eq(true, "deptId", busSaleman.getDeptId());
        cq.eq(true, "parentId", busSaleman.getParentId());
        cq.eq(true, "positionId", busSaleman.getPositionId());
        cq.eq(FlymeUtils.isNotEmpty(busSaleman.getProId()), "proId", busSaleman.getProId());
        cq.eq(FlymeUtils.isNotEmpty(busSaleman.getCityId()), "cityId", busSaleman.getCityId());
        cq.ne(FlymeUtils.isNotEmpty(busSaleman.getSaleManId()), "saleManId", busSaleman.getSaleManId());
        Long userCount = salemanService.count(cq);
        ApiAssert.lezero("人员已存在,请勿重复添加", userCount.intValue());
        return true;
    }

    private String getPositionOrder(BusSaleman busSaleman, Long companyId, String deptType) {
        //职务序号
        String positionOrder = busSaleman.getPositionOrder();
        if (FlymeUtils.isEmpty(positionOrder)) {
            CriteriaQuery cq1 = new CriteriaQuery(BusSaleman.class);
            cq1.eq(true, "deptId", busSaleman.getDeptId());
            cq1.eq(true, "positionId", busSaleman.getPositionId());
            cq1.eq(true, "companyId", companyId);
            Long count = salemanService.count(cq1);
            Long positionCount = FlymeUtils.getLong(count, 0L);
            if (DeptTypeEnum.ZY.getCode().equals(deptType)) {
                positionOrder = String.format("%02d", positionCount.intValue() + 1);
            } else {
                if (positionCount >= 1) {
                    positionOrder = String.format("%03d", positionCount.intValue() - 1 + 1);
                }
            }
            busSaleman.setPositionOrder(positionOrder);
        }
        return positionOrder;
    }


    private String getSaleManCode(BusSaleman busSaleman, Long companyId) {
        String saleManCode = busSaleman.getSaleManCode();
        //业务员设置唯一序号
        if (FlymeUtils.isEmpty(saleManCode)) {
            saleManCode = getSaleManCodeByCardNo(busSaleman);
            if (FlymeUtils.isEmpty(saleManCode)) {
                CriteriaQuery cq1 = new CriteriaQuery(BusSaleman.class);
                cq1.select("distinct saleManCode");
                cq1.eq(true, "saleManType", CommonConstants.INT_1);
                cq1.eq(true, "deptType", DeptTypeEnum.ZY.getCode());
                cq1.isNotNull("saleManCode");
                cq1.eq(true, "companyId", companyId);
                Long count = salemanService.count(cq1);
                Long saleManCount = FlymeUtils.getLong(count, 0L);
                saleManCode = String.format("%04d", saleManCount.intValue() + 1);
            }
        }
        busSaleman.setSaleManCode(saleManCode);
        return saleManCode;
    }

    private String getOrderNum(BusSaleman busSaleman) {
        String saleManOrderNum = busSaleman.getOrderNum();
        //业务员设置唯一排序号
        if (FlymeUtils.isEmpty(saleManOrderNum)) {
            Long areaId = hyOrderUtils.getAreaId(busSaleman);
            CriteriaQuery<BusSaleman> cq = new CriteriaQuery(BusSaleman.class);
            cq.select("max(orderNum) orderNum");
            cq.likeRight(true, "orderNum", areaId);
            cq.eq(true, "deptType", DeptTypeEnum.ZY.getCode());
            cq.isNotNull("saleManCode");
            String result = salemanService.getObj(cq, e -> e.toString());
            if (FlymeUtils.isNotEmpty(result)) {
                Integer count = FlymeUtils.getInteger(result, 0) + 1;
                return count.toString();
            } else {
                saleManOrderNum = areaId + "0001";
            }
        }
        return saleManOrderNum;
    }

    /**
     * 根据身份证查询已有唯一编码
     *
     * @param busSaleman
     * @return
     */
    private String getSaleManCodeByCardNo(BusSaleman busSaleman) {
        CriteriaQuery<BusSaleman> cq1 = new CriteriaQuery(BusSaleman.class);
        cq1.select("distinct saleManCode");
        cq1.eq(true, "saleManType", CommonConstants.INT_1);
        cq1.eq(true, "deptType", DeptTypeEnum.ZY.getCode());
        cq1.eq(true, "cardNo", busSaleman.getCardNo());
        cq1.limit(1);
        return salemanService.getObj(cq1, e -> e.toString());
    }
}
